package com.zm.se.controller;


import com.zm.se.entity.Emp;
import com.zm.se.entity.Equipment;
import com.zm.se.mapper.EquipmentMapper.EquMapper;
import com.zm.se.mapper.managerMapper.ManagerMapper;
import com.zm.se.service.EquService.ex.FileTypeException;
import com.zm.se.service.EquService.impl.EquServiceImpl;
import com.zm.se.util.JsonResult;
import com.zm.se.service.EquService.ex.FileUploadException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/equ")
public class EquController extends BaseController{
    @Autowired
    EquServiceImpl service;
    @Autowired
    EquMapper mapper;
    @Autowired
    ManagerMapper managerMapper;


    @RequestMapping("/delEquById")
    public JsonResult<Void> delEqu(Integer id){
        System.out.println(id);
        if ( service.delEqu(id)==1){
            return new JsonResult<>(OK);
        }
       else {
           return new JsonResult<>("shibai");
        }

    }
    @RequestMapping("/delEmpById")
    public JsonResult<Void> delEmp(Integer id){
        service.delEmp(id);
        return new JsonResult<>(OK);
    }
    @RequestMapping("/updateEmpById")
    public JsonResult<Void> updateEmp(Emp emp){
        service.updateEmp(emp);
        return new JsonResult<>(OK);
    }
    @RequestMapping("/updateEquById")
    public JsonResult<Void> updateEqu(Equipment equipment){
        service.updateEqu(equipment);
        return new JsonResult<>(OK);
    }

    @RequestMapping("/showlist")
    public JsonResult<List<Equipment>> showlist(Integer page){
        List<Equipment> list=mapper.orderequlist(page);
        for (Equipment map : list) {
            System.err.println(map);
        }
        return new JsonResult<>(OK,list);
    }
    @RequestMapping("/showprice")
    public JsonResult<List<Equipment>> showprice(Integer page){
        System.err.println("showprice执行");
        List<Equipment> list=mapper.pricelist(page);
        for (Equipment map : list) {
            System.err.println(map);
        }
        System.err.println("showprice执行完毕");
        return new JsonResult<>(OK,list);
    }

    @RequestMapping("/showsup")
    public JsonResult<List<Equipment>> showsup(Integer page){
        List<Equipment> list=mapper.suplist(page);
        for (Equipment map : list) {
            System.err.println(map);
        }
        return new JsonResult<>(OK,list);
    }
    @RequestMapping("/showEquHistory")
    public JsonResult<List<Equipment>> showEquHistory(Integer page){
        List<Equipment> list=mapper.equhistory(page);
        for (Equipment map : list) {
            System.err.println(map);
        }
        return new JsonResult<>(OK,list);
    }

    Equipment equipment=new Equipment();
    Emp emp=new Emp();

    @RequestMapping("/postNotes")
    public JsonResult<Void> postNote(Integer id, String key){
        System.out.println(id+key);
        if (key.equals("equ")){
            System.out.println(id);
           equipment=mapper.findEquById(id);
            System.out.println(equipment);
        }
        if (key.equals("emp")){
            System.out.println(id);
           emp=managerMapper.findEmpById(id);
            System.out.println(emp);

        }
        return new JsonResult<>(OK);
    }
    @RequestMapping("/getEquNotes")
    public JsonResult<Equipment> getEquNote(){
        System.out.println(equipment);
        return new JsonResult<>(OK,equipment);
    }
    @RequestMapping("/getEmpNotes")
    public JsonResult<Emp> getEmpNotes(){
        System.out.println(emp);
        return new JsonResult<>(OK,emp);
    }

    @RequestMapping("/addEqu")
    public JsonResult<String> addEqu(Equipment equipment){
        System.out.println(equipment);
        if (service.addEqu(equipment)!=1){
            return new JsonResult<>("添加失败，请重试");
        }
        return new JsonResult<>(OK);
    }
    @RequestMapping("/addEmp")
    public JsonResult<String> addEmp(Emp emp){
        System.out.println(emp);
        if (service.addEmp(emp)!=1){
            return new JsonResult<>("添加失败，请重试");
        }
        return new JsonResult<>(OK);
    }

    /**
     * 允许上传的文件类型的集合
     */
    private static final List<String> AVATAR_TYPES = new ArrayList<>();

    static {
        AVATAR_TYPES.add("application/vnd.ms-excel");
        AVATAR_TYPES.add("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");


    }
    @PostMapping("/uploadequ")
    public JsonResult<String> uploadEqu(
            @RequestParam("file") MultipartFile file, HttpSession session) {
        // 日志
        System.err.println("UserController.changeAvatar()");

        // 判断文件是否为空
        boolean isEmpty = file.isEmpty();
        System.err.println("\tisEmpty=" + isEmpty);
        if (isEmpty) {
            System.out.println("empty");

            throw new FileTypeException(
                    "上传失败！文件不能为空：" + AVATAR_TYPES);
        }
        // 获取文件的MIME类型
        String contentType = file.getContentType();
        System.err.println("\tcontentType=" + contentType);
        // 判断上传的文件类型是否符合：excel/xls
        if (!AVATAR_TYPES.contains(contentType)) {
            throw new FileTypeException(
                    "上传失败！仅允许上传以下类型的文件：" + AVATAR_TYPES);
        }

        // 获取原始文件名(客户端设备中的文件名)
        String originalFilename
                = file.getOriginalFilename();
        System.err.println("\toriginalFilename=" + originalFilename);

        if (originalFilename=="") {
            System.out.println("empty");

            throw new FileTypeException(
                    "上传失败！文件不能为空：" + AVATAR_TYPES);
        }

        // 将文件上传到哪个文件夹
        String parent = session
                .getServletContext().getRealPath("upload");
        System.err.println("\tupload path=" + parent);
        File dir = new File(parent);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 保存上传的文件时使用的文件名
        String filename = ""
                + System.currentTimeMillis()
                + System.nanoTime();
        String suffix = "";
        int beginIndex = originalFilename
                .lastIndexOf(".");
        if (beginIndex >= 1) {
            suffix = originalFilename
                    .substring(beginIndex);
        }
        String child = filename + suffix;

        // 将客户端上传的文件保存到服务器端
        File dest = new File(parent, child);
        try {
            file.transferTo(dest);
        } catch (IllegalStateException e) {
            System.out.println(
                    "上传失败！您的文件的状态异常！");
        } catch (IOException e) {
            System.out.println(
                    "上传失败！读写文件时出现错误，请重新上传！");
        }


        // 将保存的文件的路径记录到数据库中
        String avatar = "\\" + child;
        System.err.println("\tavatar path=" + avatar);
        if (originalFilename.equals("器材表.xls")||originalFilename.equals("器材表.xlsx")){
            service.ExcelReadEqu(parent,avatar);
            System.err.println("器材表录入成功");
        }else {
           throw new FileUploadException("请按要求规范文件名");
        }

        System.err.println(OK);
        return new JsonResult<>(OK);
    }


}
